<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\Group;
use App\Models\Member;
use Illuminate\Http\Request;


class GroupController extends Controller
{
    // 个人中心 - 分组列表
    public function index()
    {
        $list = Group::whereUserId(auth('wechat')->id())
            ->limit(100)
            ->get(['id', 'name']);
        return $this->writeJson(0, $list);
    }

    // 新增/编辑分组
    public function add(Request $request)
    {
        $name = $request->post('name');
        if (empty($name)) {
            return $this->writeJson(500, null, '请输入分组名称');
        }

        if ($id = $request->post('id')) {
            $model = Group::whereUserId(auth('wechat')->id())
                ->where('id', $id)
                ->first();
            if (empty($model)) {
                return $this->writeJson(500, null, '数据不存在');
            }
        } else {
            $model = new Group();
            $model->user_id = auth('wechat')->id();
        }

        $model->name = $name;
        $model->save();
        return $this->writeJson(0,null,$id ? '修改成功' : '新增成功');
    }

    // 删除分组
    public function del(Request $request)
    {
        $id = $request->post('id');
        if(empty($id)){
            return $this->writeJson(500,null,'参数错误');
        }
        // 分组下有人员，不让删除
        if (Member::whereGroupId($id)->count()) {
            return $this->writeJson(500,null,'当前分组还有人员，暂时无法删除');
        }

        Group::whereUserId(auth('wechat')->id())
            ->where('id', $id)
            ->delete();
        return $this->writeJson(0,null,'删除成功');
    }
}
